Contains duplicate II¶
Time: O(N); Space: O(N); easy
Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in the array
such that nums[i] = nums[j]
and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: True
Explanation
nums[0] = nums[3] and 3 - 0 <= 3
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: True
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: False
[2]:
class Solution1(object):
"""
Time: O(N)
Space: O(N)
"""
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
lookup = {}
for i, num in enumerate(nums):
if num not in lookup:
lookup[num] = i
else:
# If the value occurs before, check the difference.
if i - lookup[num] <= k:
return True
# Update the index of the value.
lookup[num] = i
return False
[3]:
s = Solution1()
nums = [1,2,3,1]
k = 3
assert s.containsNearbyDuplicate(nums, k) == True
nums = [1,0,1,1]
k = 1
assert s.containsNearbyDuplicate(nums, k) == True
nums = [1,2,3,1,2,3]
k = 2
assert s.containsNearbyDuplicate(nums, k) == False